//文本框
Vue.component('comp-image-phone-pull',{
  props:['fld','value'],
  data:function(){
    return {
      // fileList: this.value=='' ? [] : this.value,
      actionRemove : this.fld.actionRemove,
      qrcodeUrl:'',
      imagesUrl:'',
      token:'',
      timestamp:0,
      requestCnt:0,
      downLoading:false,
      timeImage:false,
      popoverQrcode:false,
      dialogVisible:false,
      dialogImageUrl:'',
      limit:(this.fld.limit || 1),
      action:this.fld.action,
    }
  },
  template: `
    <el-row :gutter="0">
      <div v-loading="downLoading"
           element-loading-text="图片加载中..."
           element-loading-spinner="el-icon-loading"
           element-loading-background="rgba(0, 0, 0, 0.8)" >
        <span class="el-upload-list el-upload-list--picture-card" v-for="(item,i) in fileList">
          <span class="el-upload-list__item is-success">
            <el-image
              style="width: 146px; height: 146px"
              :src="item.url"
              fit="cover"
              :preview-src-list="previewList">
            </el-image>
            <span class="el-upload-list__item-actions">
              <span class="el-upload-list__item-preview" @click="handlePreview(i,item)"><i class="el-icon-zoom-in"></i></span>
              <span class="el-upload-list__item-delete" @click="handleRemove(i,item)"><i class="el-icon-delete"></i></span>
            </span>
          </span>
        </span>

        <div tabindex="0"  class="el-upload el-upload--picture-card">
          <el-popover
            placement="top-start"
            title="请5分钟内完成上传"
            width="146"
            :value="popoverQrcode"
            @show="upload"
            trigger="click">
            <el-image
              style="width: 146px; height: 146px"
              :src="qrcodeUrl"
              fit="fill"
              title="扫码拍照上传">
                <div slot="error" class="image-slot">
                  <i class="el-icon-loading"></i>
                </div>
              </el-image>
              <el-button type="primary" slot="reference">扫码拍照</el-button>
          </el-popover>
        </div>
      </div>
      <el-dialog :visible.sync="dialogVisible" center>
        <div style="text-align:center;">
          <img style="max-width:100%;max-height:100%;" :src="dialogImageUrl" alt="" />
        </div>
      </el-dialog>
    </el-row>
  `,
  methods:{
    buildQRcode :function(){
      this.popoverQrcode = true;
      var that = this;
      var timestamp = new Date().getTime();

      if(!this.timestamp){
        this.timestamp = timestamp;
        var rand = Math.ceil(Math.random()*100000000);
        this.token = this.timestamp+''+rand;
        this.qrcodeUrl = `https://sev7.eqinfo.com.cn/login-verify-wechat/index.php?controller=Apply_Image&action=Qrcode&pull=1&token=${this.token}&limit=${this.limit}&platfrom=${this.fld.platfrom}`;
        this.imagesUrl = `https://sev7.eqinfo.com.cn/login-verify-wechat/index.php?controller=Apply_Image&action=Getimages&type=normal&tip=1&token=${this.token}`;
        //测试地址
        // this.qrcodeUrl = `http://192.168.1.95/eqinfo/login-verify/index.php?controller=Apply_Image&action=Qrcode&pull=1&token=${this.token}&limit=${this.limit}&platfrom=${this.fld.platfrom}`;
        // this.imagesUrl = `http://192.168.1.95/eqinfo/login-verify/index.php?controller=Apply_Image&action=Getimages&type=normal&tip=1&token=${this.token}`;
      }

      setTimeout(function(){
        that.getImageList();
      },3000);
    },
    upload : function(){
      if(this.fileList.length > 0){
        this.$confirm('确认重新上传吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.fileList = [];
          this.$emit('input',this.fileList);
          this.$emit('changeimg',this.fileList,this);
          //生成qrcode
          this.buildQRcode();
        }).catch(() => {
          return false;
        });
      }else{
        this.buildQRcode();
      }
    },
    getImageList : function(){
      if(this.timeImage){
        return false;
      }
      //限制请求次数
      this.requestCnt += 1;
      if(this.requestCnt > 300){
        this.requestCnt = 0;
        return false;
      }

      this.timeImage = true;
      var timeout = 1000;
      var that = this;
      var params = {};
      //去获取后台的图片，用于预览
      this.$http.get(this.imagesUrl ,params).then((res)=>{
        //如果发现本次请求有图片，则提示正在下载中
        if(res.headers['image-list-content']) {
          // console.log('response:',res);
          timeout = 100;
          // params.download = true;
          this.popoverQrcode = false;
          this.downLoading = true;
        }

        if(!res.data.images) {
          this.$notify.error({
            'title':'图片上传失败',
            'message':res.data.msg
          });
          this.timeImage = false;
          return false;
        }
        this.fileList = res.data.images || [];
        // console.log('fileList',res);
        //自动消息二维码
        if(this.fileList.length > 0){
          this.popoverQrcode = false;

          //图片加载成功后把图片保存到后台，当前列表中的图片是base64格式
          this.saveImage(this.fileList);
        }

        this.timeImage = false;
        // debugger;
        if(!res.data.images || !res.data.images.length){
          setTimeout(function(){
            that.getImageList();
          } , timeout);
        }
      }).catch(function (error) {
        that.timeImage = false;
        that.$notify.error({
          'title':'图片上传失败',
          'message':'请求失败,检查url或者其他设置'
        });
      });
    },
    saveImage : function(images){
        var that = this;
        //需要请求的数据
        var axiosPost = [];
        images.forEach((item,i)=>{
          if(parseInt(i) >= 0){
            var param = {'image':item.image ,'type':'base64'};
            var _http = this.$http.post(this.action,param);
            axiosPost.push(_http);
          }
        });

        // console.log('axiosPost=>' ,axiosPost);
        //全部请求
        var fl = [];
        // debugger;
        this.$http.all(axiosPost).then(this.$http.spread(function () {
          // console.log('arguments=>',arguments);
          for(var i in arguments){
            var json = arguments[i];
            if(json.data && json.data.imgPath){
              fl.push({name:json.data.name||json.data.imgPath ,url:json.data.imgPath ,imageId:json.data.imageId||0});
            }
          }
          // debugger;
          that.fileList = fl;
          // console.log('that.fileList:',that.fileList);
          // console.log('that.fl:',fl);

          that.$emit('input',fl);
          that.$emit('changeimg',that.fileList,that);
          that.downLoading = false;

        })).catch(function (error) {
          // debugger;
          that.$notify.error({
            'title':'请求失败',
            'message':'请求失败,检查url或者其他设置'
          });
        });
    },
    handleRemove : function(i ,item){
      // console.log(i,'=>',item);
      var that = this;
      //从服务器删除图片
      if(this.actionRemove) {
        var param = item;

        this.$http.post(this.actionRemove,param).then((res)=>{
          if(!res.data.success) {
            this.$notify.error({
              'title':'服务器删除图片失败',
              'message':'response.data.success not found'
            });
            return false;
          }
          this.fileList.splice(i ,1);
          // console.log(this.fileList);
          this.$emit('input',this.fileList);
          this.$emit('changeimg',this.fileList,this);
          this.$notify.success({
            title:'图片删除成功',
            message:res.data.msg,
          });
          //删除回调
          var key = `${this.fld.name}:remove`;
          if(this.$root.callbacks[key]){
            this.$root.callbacks[key].apply(this,arguments);
          }
        }).catch(function (error) {
          console.log('remove error :',error)
          that.$notify.error({
            'title':'请求失败',
            'message':'请求失败,检查url或者其他设置'
          });
        });
      } else {
        //如果没有设置服务器删除代码,直接删除回调
        var key = `${this.fld.name}:remove`;
        if(this.$root.callbacks[key]) return;
        this.$root.callbacks[key].apply(this,arguments);
      }
    },
    handlePreview : function(i,item){
      // var imgKey = 'item__'+i;
      // var img = this.$refs[imgKey].click();
      // console.log('images:',imgKey);
      this.dialogImageUrl = item.url;
      this.dialogVisible = true;
    },
  },
  computed: {
    previewList : function(){
      var _arr = [];
      var list = this.fileList || [];
      console.log('list',list);
      list.forEach(function(item,index){
        _arr.push(item.url);
      });
      // console.log('fileList',this.fileList);
      return _arr;
    },
    fileList : {
      get : function(){
        // console.log('fileList',value);
        if(!this.value) return [];
        return this.value;
      },
      set : function(list){
        console.log('list => ' ,list);
        this.value = list || [];
      }
    }
  },
  // mounted:function(){
  //   // this.buildQRcode();
  // }
});